package com.shuai.user.controller;

import cn.hutool.core.collection.CollectionUtil;
import com.shuai.common.constant.AuthenticationConstant;
import com.shuai.common.constant.ErrorCode;
import com.shuai.common.constant.UserConstant;
import com.shuai.common.exception.BusinessException;
import com.shuai.common.rps.BaseResponse;
import com.shuai.common.utils.MyJWTUtil;
import com.shuai.common.utils.ResultUtils;
import com.shuai.user.constant.LoginTypeEnum;
import com.shuai.user.domain.entity.User;
import com.shuai.user.domain.request.AccountLoginRequest;
import com.shuai.user.domain.request.EmailLoginRequest;
import com.shuai.user.domain.request.UserRegisterRequest;
import com.shuai.user.domain.request.UserUpdateRequest;
import com.shuai.user.domain.vo.UserVO;
import com.shuai.user.factory.LoginStrategyFactory;
import com.shuai.user.service.LoginBaseService;
import com.shuai.user.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@Validated
@RequestMapping("/users")
public class UserController {
    @Autowired
    private LoginStrategyFactory loginStrategyFactory;

    @Autowired
    private UserService userService;


    /**
     * 钉钉扫码登录回调
     * 接口地址：注意/auth与钉钉登录与分享的回调域名地址一致
     */
    @RequestMapping(value = "/auth", method = RequestMethod.GET)
    public BaseResponse<UserVO> dingdingScanCodeLogin(@RequestParam(value = "authCode") String authCode,
                                                      HttpServletResponse response) throws Exception {
        LoginBaseService scanCodeLoginService = loginStrategyFactory.getLoginStrategy(LoginTypeEnum.DINGDING_SCAN_CODE);
        User login = scanCodeLoginService.login(authCode, response);
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(login, userVO);
        return ResultUtils.success(userVO);
    }


    @PostMapping("/register")
    public BaseResponse<UserVO> register(@RequestBody @Valid UserRegisterRequest registerRequest) {
        User register = userService.register(registerRequest);
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(register, userVO);
        return ResultUtils.success(userVO);
    }


    @PostMapping("/login")
    public BaseResponse<UserVO> baseLogin(@RequestBody @Valid AccountLoginRequest accountLoginRequest,
                                          HttpServletResponse response,
                                          HttpServletRequest request) throws Exception {
        List<Cookie> cookies = Arrays.stream(request.getCookies())
                .filter(cookie -> cookie.getName().equals(UserConstant.CAPTCHA_KEY_FOR_HEADER))
                .collect(Collectors.toList());
        if (CollectionUtil.isEmpty(cookies)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请求参数丢失，请刷新后重试");
        }
        accountLoginRequest.setCaptchaCookieValue(cookies.get(0).getValue());
        LoginBaseService accountLogin = loginStrategyFactory.getLoginStrategy(LoginTypeEnum.AccountLogin);
        User user = accountLogin.login(accountLoginRequest, response);
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(user, userVO);
        return ResultUtils.success(userVO);
    }


    @PostMapping("/loginByEmail")
    public BaseResponse<UserVO> loginByEmail(@RequestBody @Valid EmailLoginRequest emailLoginRequest,
                                             HttpServletResponse response) throws Exception {
        LoginBaseService emailLoginService = loginStrategyFactory.getLoginStrategy(LoginTypeEnum.EmailLogin);
        User loginUser = emailLoginService.login(emailLoginRequest, response);
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(loginUser, userVO);
        return ResultUtils.success(userVO);
    }


    @PostMapping("/getUserInfo")
    public BaseResponse<UserVO> getUserInfo(@RequestHeader(AuthenticationConstant.AUTHENTICATION_HEADER)
                                            String authentication) {
        if (!MyJWTUtil.verifyToken(authentication)) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "异常请求");
        }
        User user = userService.getUserInfo(authentication);
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(user, userVO);
        return ResultUtils.success(userVO);
    }

    @PostMapping("/updateUserInfo")
    public BaseResponse<UserVO> updateUserInfo(
            @RequestHeader(AuthenticationConstant.AUTHENTICATION_HEADER)
            String authentication,
            @RequestBody UserUpdateRequest userUpdateRequest) {
        UserVO userVO = new UserVO();
        User user = userService.updateUserInfo(authentication, userUpdateRequest);
        BeanUtils.copyProperties(user, userVO);
        return ResultUtils.success(userVO);
    }
}
